﻿using System;
using System.Text;

namespace DotnetApp.Security
{
    internal class Sha1HashHelper : IHashHelper
    {
        public string Sha1(string text, Encoding encoding)
        {
            if (string.IsNullOrEmpty(text)) return string.Empty;

            var sha1 = System.Security.Cryptography.SHA1.Create();

            var data = sha1.ComputeHash(encoding.GetBytes(text));

            return ToHex(data);
        }

        private static string ToHex(byte[] data)
        {
            return string.Create(data.Length * 2, data, (buffer, bytes) =>
            {
                Span<char> hexAlphabet = stackalloc char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

                for (var i = 0; i < bytes.Length; i++)
                {
                    buffer[i * 2] = hexAlphabet[data[i] >> 4];
                    buffer[i * 2 + 1] = hexAlphabet[data[i] & 0xF];
                }
            });
        }
    }
}